#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

//    this->setWindowFlag(Qt::FramelessWindowHint);       //去窗口
    this->setAttribute(Qt::WA_TranslucentBackground);   //半透明背景

    tcpSocket = new QTcpSocket(this);       //创建客户端Tcp对象

    isFileMes = true;      //读取的是文件信息

    ui->sendprogressBar->setValue(0);          //设置进度条初始值

    connect(tcpSocket,&QTcpSocket::readyRead,this,&Widget::readFileHandle);     //连接读取文件的信号与槽
}

Widget::~Widget()
{
    delete ui;
}

//连接按钮
void Widget::on_connectPushButton_clicked()
{
    QString ip = ui->ipLineEdit->text();      //获取ip
    quint16 port = ui->portLineEdit->text().toUInt();       //获取端口

    tcpSocket->connectToHost(ip,port);          //连接服务器
}

//读取文件
void Widget::readFileHandle()
{
    QByteArray message = tcpSocket->readAll();          //接收信息

        if(isFileMes==true)//发送过来的是文件信息
        {
            //1、接收文件信息并拆包
            //hello##1024 拆包
            QString masgStr = QString::fromUtf8(message);
            fileName = masgStr.section("##",0,0);        //获取文件名，hello
            fileSize = masgStr.section("##",1,1).toLongLong();        //获取文件大小，1024

            //2、创建文件设置为只写
            file.setFileName(fileName);       //创建文件

            bool isOpen = file.open(QIODevice::WriteOnly);
            if(isOpen == false)
            {
                QMessageBox::warning(this,"打开文件","文件打开失败");

                tcpSocket->disconnectFromHost();        //断开连接
                tcpSocket->close();             //关闭
            }

            //初始化进度条
//            ui->sendprogressBar->setMinimum(0);     //设置进度条最小值
            ui->sendprogressBar->setMaximum(100);     //设置进度条最大值,qint64->int
            ui->sendprogressBar->setValue(0);               //设置当前值

            recFileSize = 0; // 重置接收文件大小


            isFileMes = false;      //转换标志
        }
        else        //接收的是文件内容
        {
            qint64 writelength = file.write(message);
            if(writelength != message.size())
            {
                QMessageBox::warning(this, "错误", "文件写入失败");
                file.close();
                tcpSocket->disconnectFromHost();
                return;
            }

            recFileSize += writelength;


            int progress = static_cast<int>((recFileSize * 100) / fileSize);
            ui->sendprogressBar->setValue(progress);   //更新进度条

            if(recFileSize == fileSize)
            {
                QMessageBox::information(this, "成功", "文件接收完成");
                file.close();
                isFileMes = true; // 重置标志位，准备接收下一个文件
                tcpSocket->disconnectFromHost(); // 断开连接或保持连接根据需求
            }
        }
}
